package com.vs.controller;


/*
 * testing report
 * site photos
 * tender document
 * project estimates
 * drawings
 * Bills
 * */

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.pdf.PdfPTable;
import com.lowagie.text.pdf.PdfWriter;
import com.vs.model.ExpenseForm;

public class PDFServlet extends HttpServlet{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public void init(ServletConfig config) throws ServletException{
		super.init(config);
	}
	
	public void doGet(HttpServletRequest request, 
			HttpServletResponse response) 
			throws ServletException, IOException{
		doPost(request, response);
	}
	
	@SuppressWarnings("unchecked")
	public void doPost(HttpServletRequest request, 
			HttpServletResponse response) 
			throws ServletException, IOException{
		
		response.setContentType("application/pdf"); // Code 1
		Document document = new Document();
		
		List<ExpenseForm> list = (List<ExpenseForm>)getActiveSession(request).getAttribute("expensesList");
		
		try{
			PdfWriter.getInstance(document, 
				response.getOutputStream()); // Code 2
			document.open();
			
			// Code 3
			PdfPTable table = new PdfPTable(6);
			
			table.addCell("Project Name");
			table.addCell("Expense Type");
			table.addCell("Notes");
			table.addCell("Expense Date");
			table.addCell("Pay Mode");
			table.addCell("Amount");
			
			int total =0;
			for(int i=0;i<list.size();i++)
			{
				ExpenseForm item = list.get(i);
				total+=Integer.parseInt(item.getExpenseAmount());
				table.addCell(item.getExpenseProjectName());
				table.addCell(item.getExpenseTypeName());
				table.addCell(item.getNotes());
				table.addCell(item.getExpenseDate());
				table.addCell(item.getPayMode());
				table.addCell(item.getExpenseAmount());
			}
			table.addCell("");
			table.addCell("");
			table.addCell("");
			table.addCell("");
			table.addCell("Total");
			table.addCell(total +" Rs");
			
			// Code 4
			document.add(table);		
			document.close(); 
		}catch(DocumentException e){
			e.printStackTrace();
		}
	}
	
	private HttpSession getActiveSession(HttpServletRequest request) {
		return request.getSession(false);
	}
}
